package servicies;

import java.util.ArrayList;
import java.util.List;

import model.Person;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service("personService")
public class PersonService {
	protected static final Logger logger = Logger.getLogger(PersonService.class);
	
	@Autowired
	private MongoTemplate mongoTemplate;
	
	public List<Person> getAll(){
		logger.debug("Retrieving all persons");
		List<Person> persons = new ArrayList<Person>();
		persons = mongoTemplate.findAll(Person.class);
		return persons;
		
	}
	
	public Person get(String id){
		logger.debug("Retrieving an existing person");
		Person person = new Person();
		person = mongoTemplate.findById(id, Person.class);
		return person;
	}
	
	public Boolean save(Person person){
		logger.debug("Save a person");
		try{
			mongoTemplate.save(person);
			return true;
		}catch(Exception e){
			logger.error("An error occurred while trying to save user",e);
			return false;
		}
	}
	
	public Boolean delete(Person person){
		logger.debug("Delete existing person");
		try{
			mongoTemplate.remove(person);
			return true;
		}catch(Exception e){
			logger.error("An error occured while trying to delete user",e);
			return false;
		}
	}
}
